import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
import { getToken, setToken, removeToken, getAvatar, getName, getOperatedLiveRoomId, getOrgId, setAvatar,
    setOperatedLiveRoomId, setOrgId, setName } from '../utils/auth';
import { login, logout } from '../api/login'
Vue.use(Vuex)

// 应用初始状态
const state = {
    count: 10,
    name:getName(),
    avatar:getAvatar(),
    orgId:getOrgId(),
    token:getToken(),
    //当前操作的直播间
    operatedLiveRoomId:getOperatedLiveRoomId()
}

// 定义所需的 mutations
const mutations = {
    INCREMENT(state) {
        state.count++
    },
    DECREMENT(state) {
        state.count--
    },
    SET_TOKEN: (state, token) => {
        state.token = token;
    },
    SET_NAME: (state, name) => {
        state.name = name;
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar;
    },
    SET_OLR: (state, roomId) => {
        state.operatedLiveRoomId = roomId;
    },
    SET_ORGID: (state, orgId) => {
        state.orgId = orgId
    }

}
//
const actions = {
    Login({ commit }, userInfo) {
        const username = userInfo.username.trim();
        return new Promise((resolve, reject) => {
            login(username, userInfo.password).then(response => {
                setToken(response.userInfo.token);
                setName(response.userInfo.username)
                setAvatar(response.userInfo.avatar)
                setOrgId(response.userInfo.orgId)
                commit('SET_TOKEN', response.userInfo.token);
                commit('SET_NAME', response.userInfo.username);
                commit('SET_ORGID', response.userInfo.orgId);
                commit('SET_AVATAR', response.userInfo.avatar);
                resolve();
            }).catch(error => {
                console.log(error)
                reject(error);
            });
        });
    },
    // 登出
    LogOut({ commit, state }) {
        return new Promise((resolve, reject) => {
            commit('SET_TOKEN', '');
            removeToken();
            resolve();

        });
    },
    //设置当前操作的直播间id
    SetLiveRoomId({ commit}, roomId){
        setOperatedLiveRoomId(roomId)
        commit('SET_OLR',roomId)
    }

}


// 创建 store 实例
export default new Vuex.Store({
    actions,
    getters,
    state,
    mutations
})